<template>
  <section>
    <xt-search :kw="{}" :placeholders="{}" @search="handleSearch">
      <el-input v-model="filters.keyName" :placeholder="$t('dict.dictRoleKeyName')" size="small" class="search-box__input"
                style="width:230px" clearable @keyup.enter.native="handleSearch"></el-input>
      <el-date-picker v-model="filters.startDate" type="date" :placeholder="$t('startDate')" size="small" :editable="false"
                      class="search-box__input" @change="handleSearch"></el-date-picker>
      <el-date-picker v-model="filters.endDate" type="date" :placeholder="$t('endDate')" size="small" :editable="false"
                      class="search-box__input" @change="handleSearch"></el-date-picker>
      <template slot="actions" v-if="rootModeFlag">
        <el-button size="small" class="search-box__button" type="primary" icon="plus" @click="handleAdd"
                   v-if="getOperation('insert')">{{$t('add')}}
        </el-button>
      </template>
    </xt-search>

    <!--列表-->
    <el-table :data="dictList" highlight-current-row v-loading="loading.listLoading" style="width: 100%;" stripe border>
      <el-table-column align="left" header-align="center" type="index" width="80" :label="$t('index')">
        <template slot-scope="scope">
          {{(pageInfo.pageIndex-1)*pageInfo.pageSize+scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column align="left" header-align="center" prop="keyName" :label="$t('dict.dictRoleKeyName')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="left" header-align="center" prop="value" :label="$t('dict.value')" min-width="100"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{formatterValue(scope)}}
        </template>
      </el-table-column>
      <el-table-column align="left" header-align="center" prop="remark" :label="$t('dict.remark')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <!--      <el-table-column align="left" header-align="center" prop="makeBillMan" :label="$t('makeBillMan')" min-width="100"
                             :show-overflow-tooltip="true"></el-table-column>
            <el-table-column align="left" header-align="center" prop="createDate" :label="$t('createDate')" min-width="100"
                             :show-overflow-tooltip="true"></el-table-column>
            <el-table-column align="left" header-align="center" prop="modifyDate" :label="$t('modifyDate')" min-width="100"
                             :show-overflow-tooltip="true"></el-table-column>
            <el-table-column align="left" header-align="center" prop="modifier" :label="$t('modifier')" min-width="100"
                             :show-overflow-tooltip="true"></el-table-column>-->
      <el-table-column align="left" header-align="center" :label="$t('operation')" width="150" v-if="getOperation('update|delete')">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" @click="handleEdit(scope.$index, scope.row)"
                     v-if="getOperation('update')">{{$t('modify')}}
          </el-button>
          <el-button type="danger" size="mini" @click="handleData(scope.$index, scope.row)"
                     v-if="getOperation('delete') && rootModeFlag">{{$t('delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-row>
      <el-col :span="24" class="toolbar">
        <el-pagination
          style="float:right;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.pageIndex"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageInfo.pageSize"
          layout="sizes, prev, pager, next"
          :total="pageInfo.count">
        </el-pagination>
      </el-col>
    </el-row>

    <!--新增界面-->
    <el-dialog width="70%" top="20px" :title="formData.id==0?$t('add'):$t('modify')" :visible.sync="dialog.formDataVisible"
               :close-on-click-modal="false"
               :modal-append-to-body="false">
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formData">
        <el-form-item :label="$t('dict.key')" prop="key">
          <el-input v-model="formData.key" auto-complete="off" :maxlength="50" :placeholder="$t('dict.validateKey')"
                    size="small" :disabled="formData.id !== 0"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dict.dictRoleKeyName')" prop="keyName">
          <el-input v-model="formData.keyName" auto-complete="off" :maxlength="50" :placeholder="$t('dict.validateDictRoleKeyName')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dict.value')" prop="value">
          <el-select
            style="width: 100%"
            v-model="formData.roleValueList"
            multiple
            filterable
            default-first-option
            :placeholder="$t('dict.validateDictRoleValue')">
            <el-option
              v-for="(item,index) in roleList"
              :key="index"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dict.remark')" prop="remark">
          <el-input type="textarea" resize="none" v-model="formData.remark" auto-complete="off" :maxlength="100"
                    :placeholder="$t('dict.validateRemark')" size="small"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleCancel">{{$t('cancel')}}</el-button>
        <el-button type="primary" @click.native="submitData" :loading="loading.addLoading">{{$t('submit')}}</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

  /*#region 导入函数*/
  import PagePlugIn from "../../../mixins/page-plug-in";
  import {UrlParamUtil} from "../../../utils/utils.js";
  import {DictAPI, RoleAPI} from "../../../modules";
  import {SystemParameterEnum} from "../../../modules/enums";

  /*#endregion*/

  export default {
    name: "DictRoleBind",
    methods: {

      /*#region 自定义函数(组件change事件等)*/
      formatterValue(row) {
        let value = row.row.value;
        if (this.roleList !== undefined && this.roleList.length > 0) {
          value = row.row.roleValueList.map((id) => (this.roleList.find((role) => role.id === id) || {name: ""}).name).filter(Boolean)
          .join(",");
        }
        return value;
      },

      /*#endregion*/

      /*#region 数据提交事件*/
      //删除
      handleData(index, row) {
        this.$confirm(this.$t('deleteConfirm'), this.$t('tips'), {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: "warning"
        }).then(() => {
          DictAPI.deleteDict({id: row.id}).then(({res}) => {
            if (res.data.code === 1) {
              this.getMainList();
            }
          });
        });
      },
      //提交事件
      submitData() {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            const _formData = Object.assign({}, this.formData);

            _formData.type = SystemParameterEnum.DictRoleBindType.type;
            _formData.editFlag = true;
            _formData.displayFlag = false;
            _formData.value = _formData.roleValueList.join(",");
            delete _formData.roleValueList;

            const params = JSON.parse(JSON.stringify(_formData));
            if (params.id === 0) {
              this.loading.addLoading = true;
              DictAPI.insertDict(params).then(({res}) => {
                if (res.data.code === 1) {
                  this.$refs.formData.resetFields();
                  this.getMainList();
                  this.dialog.formDataVisible = false;
                }
                this.loading.addLoading = false;
              });
            } else {
              this.loading.addLoading = true;
              DictAPI.updateDict(params).then(({res}) => {
                if (res.data.code === 1) {
                  this.$refs.formData.resetFields();
                  this.getMainList();
                  this.dialog.formDataVisible = false;
                }
                this.loading.addLoading = false;
              });
            }
          }
        });
      },

      /*#endregion*/

      /*#region 操作函数(handle)*/
      //修改
      handleEdit(index, row) {
        this.$refs.formData && this.$refs.formData.resetFields();
        this.formData = JSON.parse(JSON.stringify(row));
        this.dialog.formDataVisible = true;
      },
      handleCancel() {
        this.dialog.formDataVisible = false;
      },
      handleAdd() {
        this.$refs.formData && this.$refs.formData.resetFields();
        this.formData = {...DictAPI.init(), roleValueList: []};
        this.dialog.formDataVisible = true;
      },

      /*#endregion*/

      /*#region 获取数据*/
      getMainList() {
        const params = {
          ...this.getParams()
        };
        params.type = SystemParameterEnum.DictRoleBindType.type;
        params.orderBy = "Id desc";
        DictAPI.listDict(params).then(({res, list}) => {
          this.dictList = list ? list : [];
          this.dictList.map((item) => {
            const numbersList = item.value ? item.value.split(",").map((i) => Number(i)) : [];
            this.$set(item, "roleValueList", numbersList);
          });
          this.pageInfo.pageIndex = res.data.data ? res.data.data.currentPage : 1;
          this.pageInfo.count = res.data.data ? res.data.data.count : 0;
        });
      }

      /*#endregion*/
    },

    /*#region 生命周期函数(created、mount、等)*/
    created() {
      const mode = UrlParamUtil.getUrlParam("mode");
      if (mode && mode === "whosyourdaddy") {
        this.rootModeFlag = true;
      }
      this.getMainList();
      //角色
      RoleAPI.listRole({pageSize: 999999}).then(({res, list}) => {
        this.roleList = list ? list : [];
      });
    },

    /*#endregion*/

    /*#region 注册绑定数据*/
    components: {},
    mixins: [PagePlugIn],
    data() {
      return {
        filters: DictAPI.init(),
        dictList: [],
        formData: {...DictAPI.init(), roleValueList: []},
        formRules: {
          keyName: [{required: true, message: this.$t('dict.validateDictRoleKeyName')}],
          key: [{required: true, message: this.$t('dict.validateKey')}]
        },
        dialog: {formDataVisible: false},
        loading: {addLoading: false, listLoading: false},
        roleList: [],
        rootModeFlag: false
      };
    }

    /*#endregion*/
  };
</script>

<style scoped>

</style>
